package array.Binary_Search;
/*      给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。

        请必须使用时间复杂度为 O(log n) 的算法。

        示例 1:
        输入: nums = [1,3,5,6], target = 5
        输出: 2

        示例 2:
        输入: nums = [1,3,5,6], target = 2
        输出: 1

        示例 3:
        输入: nums = [1,3,5,6], target = 7
        输出: 4*/
public class lc35 {
    public static void main(String[] args) {
        int[] nums=new int[]{1,4,5,9,12,15};
        System.out.println(searchInsert(nums, 11));

        int[] nums2=new int[]{1,4,5,9};
        System.out.println(searchInsert(nums2, 8));

    }
    public static int searchInsert(int[] nums, int target) {
        if(target>nums[nums.length-1]){
            return nums.length;
        } else if (target<nums[0]) {
            return 0;
        }
        int location=-1;
        int low=0;
        int high=nums.length-1;
        int mid=low+(high-low)/2;
        while(low<=high){
            mid=low+(high-low)/2;
            if(nums[mid]>target){
                high=mid-1;
            } else if (nums[mid]<target) {
                low=mid+1;
            } else if (nums[mid]==target) {
                location=mid;
                return mid;
            }
        }
        System.out.println(mid);
        if(nums[mid]<target){
            return mid+1;
        } else if (nums[mid]>target) {
            return  mid;
        }
        return -2;
    }
}
